<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\logic\TeamOrderLogic;
use app\common\logic\TeamFoundLogic;
use think\Db;



/**
 * 拼团开团接口
 */
class TeamFound extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $team; //拼团模型
    protected $teamFound; //开团模型
    protected $goods; //商品模型
    protected $order; //订单模型
    protected $teamFollow; //参团模型


    public function _initialize()
    {
        parent::_initialize();
//        $this->model = new \app\common\model\TeamFound();
        $this->team = new \app\common\model\TeamActivity();
        $this->teamFound = new \app\common\model\TeamFound();
        $this->goods = new  \app\common\model\Goods();
        $this->order = new \app\common\model\Order();
        $this->teamFollow = new \app\common\model\TeamFollow();
    }


    /**
     * found_id 开团id
     * 拼团页
     */
    public function pintuan(){
        $found_id = $this->request->request('found_id');
        $teamFoundLogic = new TeamFoundLogic();
        $teamFound = $this->teamFound->get($found_id);
        $team = $this->team->get($teamFound['team_id']);
        $teamFoundLogic->setTeam($team);
        $teamFoundLogic->setTeamFound($teamFound);
        $res = $teamFoundLogic->TeamFoundIsCanFollow();

        $teamFollow = $this->teamFollow->where(['found_id' => $teamFound['id']])->find();

        if($teamFollow){
            $canTuanTime = $teamFollow['follow_time'];
            $order = Db::name('order')->where('id',$teamFollow['order_id'])->find();
            $address =Db::name('address')->where('id',$order['address_id'])->find();
        }else{
            $canTuanTime = $teamFound['found_time'];
            $order = Db::name('order')->where('id',$teamFound['order_id'])->find();
            $address =Db::name('address')->where('id',$order['address_id'])->find();
        }


        if($res['code'] == 1){
            //能拼
            $goods = $this->goods->get($team['goods_id']);
            $pintuansheng = ($goods['shop_price']*100 - $team['team_price']*100)/100;
            $shengYuMingE = $teamFound['need'] - $teamFound['join'];
            $daoJiShi = $teamFound['daojishi_text'];

            $pinTuanGuiZe = \app\common\model\Page::getPagesByCategoryName('拼团须知');

            //用户是否参过团
//            $isFollow = Db::name('team_follow')->where(['found_id' => $teamFound['id'], 'follow_user_id' => $this->auth->id])->count();
            $teamOrderLogic = new \app\common\logic\TeamOrderLogic();

            $isEnble = $teamOrderLogic->isHasTeamFollow($teamFound['id'],$this->auth->id);
            $isEnble ? $isJoinTeam = 1 : $isJoinTeam = 0;


            $data = [
                'found_id' => $teamFound['id'],
                'goods_id' => $team['goods_id'],
                'item_id' => $team['item_id'],
                'isJoinTeam' => $isJoinTeam,
                'image' => $goods['image'],
                'name' => $team['name'],
                'pinTuanSheng' => $pintuansheng,
                'team_price' => $team['team_price'],
                'market_price' => $goods['market_price'],
                'shengYuMingE' => $shengYuMingE,
                'daoJiShi' => $daoJiShi,
                'canTuanTime' => $canTuanTime,
                'teamFollowList' => $teamFound['team_follow_text'],
                'address' => $address,
                'pinTuanGuiZe' => $pinTuanGuiZe
            ];

            $this->success('',$data);

        }else{
            $teamActivity = $teamFound->teamActivity;
            $store_count = Db::name('goods')->where('id',$team['goods_id'])->value('store_count');
            $teamActivity['store_count'] = $store_count;

            $res['data']['teamActivity'] = $teamActivity;
            $res['data']['address'] = $address;

            if($res['code'] == 2){
                //拼团成功
                $this->error($res['msg'],$res['data'],2);

            }else{
                //拼团失败
                $this->error($res['msg'],$res['data']);
            }

        }
    }


    /**
     * 个人中心
     * 我的拼团页面
     */
    public function myTeamFound()
    {
        /*开团数据*/
        $this->dataLimit = true;
        list($where, $sort, $order, $offset, $limit , $field) = $this->buildparams();

        $total = $this->teamFound

            ->where($where)
            ->where(function ($query){
                $query->where('status','<>',0);
            })
            ->order($sort, $order)
            ->count();

        $teamFoundList = $this->teamFound
//            ->with('goods')
            ->field($field)
            ->where($where)
            ->where(function ($query){
                $query->where('status','<>',0);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();


        /****************************/

        /** 参团数据 **/
        $teamFollowData = Db::name('team_follow')
            ->where(['follow_user_id' => $this->auth->id,'status' => ['<>',0]])
//            ->where(['follow_user_id' => $this->auth->id])
            ->order('follow_time desc')
            ->select();
//        dump($teamFollowList);exit;

        $teamFoundData = [];
        $teamFollowList = [];
        foreach ($teamFollowData as $k => $v){
            $teamFoundData = $this->teamFound->get($v['found_id'])->toArray();
            $teamFollowList[$k]['team_follow_text'] = $teamFoundData['team_follow_text'];
            $teamFollowList[$k]['goods_info_text'] = $teamFoundData['goods_info_text'];

            $teamFollowList[$k]['id'] = $v['found_id'];
            $teamFollowList[$k]['found_time'] = $v['follow_time'];
            $teamFollowList[$k]['found_end_time'] = $teamFoundData['found_end_time'];
            $teamFollowList[$k]['user_id'] = $v['follow_user_id'];
            $teamFollowList[$k]['team_id'] = $v['team_id'];
            $teamFollowList[$k]['order_id'] = $v['order_id'];
            $teamFollowList[$k]['join'] = $teamFoundData['join'];
            $teamFollowList[$k]['need'] = $teamFoundData['need'];
            $teamFollowList[$k]['price'] = $teamFoundData['price'];
            $teamFollowList[$k]['goods_price'] = $teamFoundData['goods_price'];
            $teamFollowList[$k]['status'] = $v['status'];
            $teamFollowList[$k]['nickname'] = $v['follow_user_nickname'];
            $teamFollowList[$k]['avatar'] = $v['follow_user_avatar'];
            $teamFollowList[$k]['daojishi_text'] = $teamFoundData['daojishi_text'];
            $teamFollowList[$k]['shengyuminge_text'] = $teamFoundData['shengyuminge_text'];
            $teamFollowList[$k]['status_text'] = $teamFoundData['status_text'];
        }

        //合并开团，参团数据
        $list  = array_merge($teamFoundList,$teamFollowList);
//        dump($teamFollowList);exit;
//        array_multisort(array_column($list, 'found_time'),SORT_DESC,$list);

//        dump($list);exit;

        //拼团状态:0=待开团(表示已下单但是未支付),1=已经开团(团长已支付),2=拼团成功,3=拼团失败
        foreach($list as $k => $v){
            $found_time[$k] = $v['found_time'];

           if($v['status'] == 1){
               //拼团中
               $list[$k]['status_text_msg'] = "拼团中，还差" . $v['shengyuminge_text'] . "人";
               $list[$k]['status_text_desc'] = "还差" .$v['shengyuminge_text']. "人,剩余" . secToTime($v['daojishi_text']);
           }elseif($v['status'] == 2){
               //拼团成功
               $list[$k]['status_text_msg'] = "拼团成功";
               $list[$k]['status_text_desc'] = $v['need'] . "人拼团，已完成";
            }elseif($v['status'] == 0){
               //拼团中，未支付
               $list[$k]['status_text_msg'] = "拼团未支付";
               $list[$k]['status_text_desc'] = $v['join']."人参与，未完成";
           }else{
               //拼团失败
               $list[$k]['status_text_msg'] = "拼团失败，已退款";
               $list[$k]['status_text_desc'] = $v['join']."人参与，未完成";
           }
        }

        array_multisort($found_time, SORT_DESC, $list);

        $result = array("total" => $total, "rows" => $list);
        $this->success('',$result);
    }

}